<template>
  <view class="create-map container">
    <u--form
      labelPosition="left"
      labelWidth="100"
      :model="addressInfo"
      :rules="rules"
      ref="addressForm"
    >
      <u-form-item label="联系人" prop="name" required>
        <u--input
          v-model="addressInfo.name"
          border="none"
          inputAlign="center"
          placeholder="请填入姓名"
          :customStyle="style"
          :clearable="true"
        ></u--input>
      </u-form-item>
      <u-form-item label="联系人电话" prop="phone" required>
        <u--input
          v-model="addressInfo.phone"
          :customStyle="style"
          placeholder="请填入联系电话"
          inputAlign="center"
          :clearable="true"
          border="none"
        ></u--input>
      </u-form-item>
      <u-form-item
        label="地址"
        prop="address"
        @click="handleShowPicker"
        required
      >
        <u--input
          v-model="addressInfo.address"
          :customStyle="style"
          :disabled="true"
          :clearable="true"
          inputAlign="center"
          placeholder="省、市、区、街道"
          suffixIcon="map-fill"
          suffixIconStyle="color: #C94117;margin-right: 8rpx;"
          border="none"
        ></u--input>
      </u-form-item>
      <u-form-item label="详情地址" prop="addressDetail" required>
        <u--input
          v-model="addressInfo.addressDetail"
          :customStyle="style"
          :clearable="true"
          inputAlign="center"
          placeholder="请填入详情地址"
          suffixIcon="map-fill"
          suffixIconStyle="color: #C94117;margin-right: 8rpx;"
          border="none"
        ></u--input>
      </u-form-item>
      <u-form-item label="设为默认服务地址" labelWidth="150">
        <u-switch
          slot="right"
          activeColor="#C94117"
          v-model="defaultValue"
          @change="handleIsDefault"
        ></u-switch>
      </u-form-item>
    </u--form>
    <u-picker
      :show="showPicker"
      ref="addressPicker"
      :columns="columns"
      @confirm="confirm"
      @cancel="cancel"
      @change="changeHandler"
    ></u-picker>
    <button
      class="circle-button btn-active"
      style="width: 90%"
      @click="createAddress"
    >
      确定
    </button>
  </view>
</template>

<script>
import { createModel, getModelInfo, updateModel } from "@/api";
export default {
  data() {
    return {
      addressInfo: {
        name: "",
        phone: "",
        address: "",
        addressDetail: "",
        isDefault: 0,
        location: "",
      },
      defaultValue: false,
      rules: {
        name: {
          type: "string",
          required: true,
          message: "请填写姓名",
          trigger: ["blur", "change"],
        },
        phone: {
          type: "string",
          required: true,
          message: "请填写手机号",
          trigger: ["blur", "change"],
        },
        address: {
          type: "string",
          required: true,
          message: "请填写地址",
          trigger: ["change"],
        },
        addressDetail: {
          type: "string",
          required: true,
          message: "请填写详情地址",
          trigger: ["change"],
        },
      },
      style: {
        backgroundColor: "#EEE",
        height: "68rpx",
      },
      showPicker: false,
      columns: [],
      columnData: [],
      threeColumns: [],
      planLocate: "请选择地址",
      addressId: "",
      fistId: "",
    };
  },
  methods: {
    handleShowPicker() {
      this.showPicker = true;
    },
    // 回调参数为包含columnIndex、value、values
    confirm(e) {
      let { value, columnIndex } = e;
      if (columnIndex < 2) {
        uni.showToast({ title: "请选择完整地址", icon: "none" });
        return;
      }
      this.addressInfo.address = value.join("");
      this.showPicker = false;
    },
    // 取消选择器
    cancel() {
      this.showPicker = false;
    },
    // 选择器值变化时触发
    handleIsDefault(e) {
      if (e) {
        this.addressInfo.isDefault = Date.now();
      } else {
        this.addressInfo.isDefault = 0;
      }
    },
    // 选择器值变化时触发
    changeHandler(e) {
      const {
        columnIndex,
        value,
        values, // values为当前变化列的数组内容
        index,
        indexs,
        // 微信小程序无法将picker实例传出来，只能通过ref操作
        picker = this.$refs.addressPicker,
      } = e;
      console.log("change", e);

      // 当第一列值发生变化时，变化第二列(后一列)对应的选项
      if (columnIndex === 0) {
        // picker为选择器this实例，变化第二列对应的选项
        picker.setColumnValues(1, this.columnData[index]);
        picker.setColumnValues(2, this.threeColumns[index][0]);
      } else if (columnIndex === 1) {
        picker.setColumnValues(2, this.threeColumns[indexs[0]][index]);
      }
    },
    // allAddress
    cityUtile(data) {
      let arr = data;
      // 提取所有省份
      let province = arr.reduce(this.getProvince, []);
      let city = arr.reduce(this.getCity, []);
      let district = arr.reduce(this.getDistrict, []);
      this.columnData = [...city];
      this.threeColumns = [...district];
      this.columns = [province, city[0], district[0][0]];
    },
    // 提取所有省份
    getProvince(prev, cur) {
      prev.push(cur.provinceName);
      return prev;
    },
    // 提取所有城市
    getCity(prev, cur) {
      let cityList = cur.city.map((item) => item.cityName);
      prev.push(cityList);
      return prev;
    },
    // 提取所有区县
    getDistrict(prev, cur) {
      let arr = cur.city.map((item) => item.county.map((i) => i.countyName));
      let districtList = arr;
      prev.push(districtList);
      return prev;
    },
    // 创建地址
    async createAddress() {
      try {
        const locationData =
          this.addressInfo.address + this.addressInfo.addressDetail;
        const { location } = await this.$helper.getCurrentLocation(
          locationData
        );
        this.addressInfo.location = Object.values(location).join(",");

        const res = this.addressId
          ? await updateModel(
              "65c1d9085efd5153ff55e6f4",
              this.addressInfo,
              this.addressId
            )
          : await createModel("65c1d9085efd5153ff55e6f4", this.addressInfo);

        if (res.code === 200) {
          uni.showToast({
            title: this.addressId ? "修改成功" : "创建成功",
            icon: "success",
            duration: 600,
          });

          setTimeout(() => {
            uni.navigateBack();
          }, 600);
        }
      } catch (error) {
        console.error("Error in createAddress:", error);
      }
    },
    // 获取编辑地址表单数据
    async editAddress(id) {
      let res = await getModelInfo("65c1d9085efd5153ff55e6f4", id);
      if (res.code === 200) {
        this.addressInfo = res.data;
      } else {
        uni.showToast({
          title: "获取地址失败",
          duration: 600,
          icon: "error",
        });
      }
    },
  },
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.addressForm.setRules(this.rules);
  },

  async onLoad({ addressId, firstId }) {
    this.fistId = firstId;
    this.defaultValue = firstId && firstId === addressId ? true : false;
    // 获取三级联动数据
    await uni.request({
      url: "https://kindoucloud.com:8018/address.json",
      success: (res) => {
        // console.log(JSON.parse(res?.data.slice(1, -1)));
        if (res.statusCode !== 200) {
          uni.showToast({
            title: "获取地址失败",
            duration: 600,
            icon: "error",
          });
          return;
        }
        this.cityUtile(JSON.parse(res?.data.slice(1, -1)));
        // this.columns = res.data;
      },
      fail: (err) => {
        console.log(err);
      },
    });
    // 获取当前表单数据
    this.addressId = addressId;
    if (!addressId) return;
    this.editAddress(addressId);
  },
};
</script>

<style lang="scss" scoped>
.create-map {
  position: relative;
  background-color: #fff;

  button {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    bottom: constant(safe-area-inset-bottom) !important;
    bottom: env(safe-area-inset-bottom) !important;
  }
}

::v-deep .u-form {
  background-color: #fff;
  border-radius: 10rpx;

  &-item {
    padding: 0 30rpx;

    &__body {
      padding: 12px 0;
    }

    &__body__left__content__label {
      margin-left: 8rpx;
    }
  }

  input {
    // text-align: right !important;
    height: 68rpx !important;
  }

  .u-icon--right {
    // margin-left: 8rpx;
  }
}
</style>
